import logging
from ninja import Router, Query
from django.utils import timezone

from apps.commom.good import GoodSerializer, GoodSimpleSerializer, GoodTypeSerializer
from apps.user_applets.good.schemas import AppletGoodFiltersSchema
from apps.schemas import R
from apps.user_applets.shop_cart.schemas import AddShopCartSchema
from models.choices import WaterCardType
from models.models import Goods, BrowsingRecord, SearchRecord, ShopCart, WaterDropletsTask, WaterDropletsRecord, \
    GoodType
from utils.auth import AppletAuthBearer
from utils.decorators import handle_exception

good_applet_router = Router(tags=["前端商品"], auth=AppletAuthBearer())


@good_applet_router.get("/good_types", summary="获取商品分类")
@handle_exception("没有找到相关商品分类")
def get_good_types(request):
    good_types = GoodType.objects.all()
    return R.ok(data=GoodTypeSerializer(good_types, many=True).data)


@good_applet_router.get("/goods", summary="获取商品")
@handle_exception("没有找到相关商品")
def get_goods(request, filters: AppletGoodFiltersSchema = Query(...)):
    goods = Goods.objects.filter(name__contains=filters.name, status=1)
    if filters.type_id:
        goods = goods.filter(type__id=filters.type_id)
    if filters.name:
        # 添加搜索记录
        if not SearchRecord.objects.filter(user=request.user, keyword=filters.name).exists():
            SearchRecord.objects.create(user=request.user, keyword=filters.name)
    if not goods:
        return R.ok(msg="没有找到相关商品")
    if filters.price_up:
        goods = goods.order_by("goodspecification__price")
    if not filters.price_up and filters.price_up is not None:
        goods = goods.order_by("-goodspecification__price")
    if filters.sales_up:
        goods = goods.order_by("sales_number")
    if not filters.sales_up and filters.sales_up is not None:
        goods = goods.order_by("-sales_number")
    return R.ok(data=GoodSimpleSerializer(goods, many=True).data)


@good_applet_router.get("/good/{good_id}", summary="获取商品详情")
@handle_exception("没有找到相关商品")
def get_good(request, good_id):
    # todo 点击次数加1
    good = Goods.objects.get(id=good_id)
    good.browsing_number += 1
    good.save()
    # todo 添加浏览浏览记录
    if BrowsingRecord.objects.filter(user=request.user, good=good).exists():
        for item in BrowsingRecord.objects.filter(user=request.user, good=good):
            item.save()
    else:
        BrowsingRecord.objects.create(user=request.user, good=good)
    return R.ok(data=GoodSerializer(good).data)


@good_applet_router.post("/good/add/shop_cart", summary="添加商品到购物车")
@handle_exception("添加商品到购物车失败")
def add_shop_cart(request, data: AddShopCartSchema):
    if not Goods.objects.filter(id=data.good_id).exists():
        logging.error(f"未查寻到相关商品， id为： {data.good_id}")
        return R.ok(msg="没有找到相关商品")
    good = Goods.objects.get(pk=data.good_id)
    if ShopCart.objects.filter(user=request.user, good=good, spec_id=data.spec_id).exists():
        shop = ShopCart.objects.filter(user=request.user, good=good, spec_id=data.spec_id).first()
        shop.good_number += data.good_number
        shop.save()
    else:
        ShopCart.objects.create(user=request.user, good=good, spec_id=data.spec_id, good_number=data.good_number)
    good.shopping_cart_number += 1
    good.save()
    task = WaterDropletsTask.objects.get(id=3)
    if task.on:
        # 用户水滴增加
        user = request.user
        user.water_droplets_number += task.droplet_number
        user.save()
        # 新增水滴记录
        WaterDropletsRecord.objects.create(user_id=user.id, op_type=WaterCardType.GET,
                                           droplet_number=task.droplet_number, op_time=timezone.now())
    return R.ok(msg="添加成功")
